<?php
/**
 * Holds class DBStatement
 *
 * @author daantimmer
 * @see PDOStatement
 *
 * @package Library
 */

/**
 * Extension to PDOStatement
 *
 * This version has two extra functions and it also times all queries.
 * Keeps track of succesful queries and failed queries
 *
 * @author daantimmer
 */
class DBStatement extends PDOStatement{
	
	private static $short = null;
	private static $long = null;
	private static $executeFail = 0;
	private static $fetchObjFail = 0;
	
	/**
	 * @param string class_name
	 * @param array ctor_args
	 * @return mixed
	 */
	public function fetchObjectOnce ($class_name = 'stdClass', $ctor_args = array()) {
		$time = $this->start();
		if($this->execute() === false)
			return $this->endExecute($time,null);
		
		$return = $this->fetchObject($class_name,$ctor_args);
		
		if($return === false)
			return $this->endFetchObject($time,null);
		
		return $this->end($time,$return);
	}
	
	/**
	 *
	 * @param string $class_name
	 * @param array $ctor_args
	 * @param array $args
	 * @return array
	 */
	public function fetchObjectAll($class_name = 'stdClass', $ctor_args = array(), $args = null){
		$time = $this->start();
		if($this->execute($args) === false)
			return $this->endExecute($time,null);
		
		$return = array();
		
		while(($val = $this->fetchObject($class_name,$ctor_args)) !== false)
			$return[] = $val;
			
		if(count($return) === 0)
			return $this->endFetchObject($time,null);
		
		return $this->end($time,$return);
	}
	
	public static function getShortTime(){return DBStatement::$short;}
	
	public static function getLongTime(){return DBStatement::$long;}
	
	public static function getExecuteFailCount(){return DBStatement::$executeFail;}
	
	public static function getFetchObjFailCount(){return DBStatement::$fetchObjFail;}
	
	private function start(){
		return Util::getMicrotime();
	}
	
	private function end($time, $return){
		$end = Util::getMicrotime();
		$time = $end-$time;
		
		if(DBStatement::$short === null)	DBStatement::$short = $time;
		elseif($time < DBStatement::$short)DBStatement::$short = $time;
		
		if(DBStatement::$long === null)	DBStatement::$long = $time;
		elseif($time > DBStatement::$long)	DBStatement::$long = $time;
		
		return $return;
	}
	
	private function endExecute($time,$return){
		DBStatement::$executeFail++;
		return $this->end($time,$return);
	}
	
	private function endFetchObject($time,$return){
		DBStatement::$fetchObjFail++;
		return $this->end($time,$return);
	}
}